const _request = require("../../utils/request.js");
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mallimgUrl: app.globalData.mallimgUrl,
    isShopcarEmpty: true,
    goodsList: [],
    editFlag: false,
    randomGoodsList: [],
    btnText: '编辑',
    allCheckFlag: false,
    selectgoodsNum: 0
  },

  toEdit() {
    
    this.setData({
      editFlag: !this.data.editFlag
    })

    const text = this.data.editFlag ? '完成': '编辑'

    let list = this.data.goodsList
    const self = this
    list.forEach(e => {
      if (!self.data.editFlag) {
        e.checked = false
      } else {
        e.activeClass = ''
      }
    })
    this.setData({
      goodsList: list,
      btnText: text
    })
  },

  showDel(event) {
    if (this.data.editFlag) {
      return
    }
    let list = this.data.goodsList
    const self = this
    list.forEach(e => {
        e.activeClass = event.currentTarget.dataset.id == e.id ? (e.activeClass === 'active-right' ? '' : 'active-right'): ''
    })
    this.setData({
      goodsList: list
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getRandomProduct()
    this.queryShopCarInfo()
  },

  getRandomProduct: function() {
    const self = this
    _request.get('/commodity/getRandomProduct', {
    }, app.globalData.mallType).then((res) => {
      if (res.data.code === 200) {
        let list = res.data.data || []
        self.setData({
          randomGoodsList: list
        })
      }
    })
  },
  gotoNext: function(item) {
    wx.navigateTo({
      url: '/pages/shopingmall/goodsdetail' + this.getparams(item.currentTarget.dataset)
    })
  },
  getparams: function(item) {
    const list = []
    for(const key in item) {
      if (key === 'url') {
        continue;
      }
      list.push(key + '=' + item[key])
    }

    if (list.length) {
      return '?' + list.join('&')
    } else {
      return '';
    }

  },
  delBtn(event) {
    const goodsid = event.currentTarget.dataset.goodsid
    wx.showModal({
      title: '确定要删除该商品吗?',
      success: (res) => {
        if (res.confirm) {
          this.handleDel( [goodsid])
        } else if (res.cancel) {}
      },
    })
  },

  handleDel(ids) {
    const self = this
    _request.postObj('/shoppingTrolley/updateShoppingTrolleyDeleteStatus', {
      idList: ids.join(',')
    }, app.globalData.mallType).then((res) => {
      if (res.data.code === 200) {
        let list = self.data.goodsList || []
        let ind
        list.forEach((e, index) => {
          if (e.id == goodsid) {
            ind = index
          }
        })
        list.splice(index, 1)
        self.setData({
          goodsList: list,
          isShopcarEmpty: list.size() === 0
        })
        self.countSelectGoodsNum()
      }
    })

  },

  queryShopCarInfo() {
    const self = this
    _request.get('/shoppingTrolley/getShoppingTrolleyListByUserId', {
      id: wx.getStorageSync('userId')
    }, app.globalData.mallType).then((res) => {
      if (res.data.code === 200) {
        // console.log(res.data.data)
        let list = res.data.data.rows || []
        list.forEach(e => {
          e.spObj = JSON.parse(e.sp1 || '[{"key":"颜色","value":"银色"},{"key":"容量","value":"32G"}]');
          let list = []
          e.spObj.forEach(item => {
            list.push(item.key + ":" + item.value)
          })
          e.spType =  list.join(',')
          e.checked = false
        })
        self.setData({
          goodsList: list,
          isShopcarEmpty: (res.data.data.rows || []).length === 0
        })
        self.countSelectGoodsNum()
      }
    })
  },

  addBuyNum(event) {
    console.log(event)
    const id = event.currentTarget.dataset.id
    const skuId = event.currentTarget.dataset.skuid
    let list = this.data.goodsList
    list.forEach(e => {
      if (e.id == id && e.productSkuId == skuId) {
        e.quantity = e.quantity + 1
      }
    })
    this.setData({
      goodsList: list
    })
  },

  gotoHome() {
    wx.reLaunch({
      url: '/pages/shopingmall/index',
    })
  },

  singleSelect(event) {
    const id = event.currentTarget.dataset.id
    const skuId = event.currentTarget.dataset.skuid
    let list = this.data.goodsList
    list.forEach(e => {
      if (e.id == id && e.productSkuId == skuId) {
        e.checked = !e.checked
      }
    })
    this.countSelectGoodsNum()
    this.setData({
      goodsList: list
    })
  },
  countSelectGoodsNum() {
    let selectgoodsNum = 0
    let list = this.data.goodsList
    list.forEach(e => {
      if (e.checked) {
        selectgoodsNum++
      }
    })
    this.setData({
      selectgoodsNum: selectgoodsNum
    })
  },
  selectAllFn() {
    this.setData({
      allCheckFlag: !this.data.allCheckFlag
    })
    let list = this.data.goodsList
    const self = this
    list.forEach(e => {
      e.checked = self.data.allCheckFlag
    })
    this.setData({
      goodsList: list
    })
    this.countSelectGoodsNum()
  },

  delAll() {
    let list = this.data.goodsList
    let delList = list.filter(e => e.checked)
    if (!delList.length) {
      return;
    }

    wx.showModal({
      title: '确定要删除选中商品吗?',
      success: (res) => {
        if (res.confirm) {
          let ids = delList.map(e => e.id)
          this.handleDel(ids)
        } else if (res.cancel) {}
      },
    })
  },

  iconclick(){

  },
  gotoOrder () {
    let list = this.data.goodsList

    let delList = list.filter(e => e.checked)

    if (!delList.length) {
      wx.showToast({
        title: '请选择需要购买的商品',
        icon: 'none',
        duration: 1000
      })
      return;
    }

    // let buyGoodsList = delList.map(e => {
    //   return {
    //     productId: e.id,
    //     productAttribute: e.productAttr,
    //     productNumber: e.quantity || 1,
    //     productSkuId: e.productSkuId
    //   }
    // })

    // console.log({
    //   userId: wx.getStorageSync('userId'),
    //   goodsList: buyGoodsList
    // })

    wx.navigateTo({
      url: '/pages/shopingmall/order'
    })
    // const self = this
    // _request.postObj('/order/previewOrder', {
    //   userId: wx.getStorageSync('userId'),
    //   goodsList: buyGoodsList
    // }, app.globalData.mallType).then((res) => {
    //   if (res.data.code === 200) {
    //     wx.navigateTo({
    //       url: '/pages/shopingmall/order',
    //     })
    //   }
    // })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})